/*
 * Copyright 2012 yura.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.opu.pc.security;

import org.opu.pc.domain.SystemSettingsManagement;
import org.opu.pc.domain.SystemSettingsManagement.DefaultAuthenticationOption;
import static org.opu.pc.domain.SystemSettingsManagement.Option.*;
import static org.opu.pc.domain.SystemSettingsManagement.DefaultAuthenticationOption.*;
import org.opu.pc.domain.UserManagement;
import org.springframework.security.authentication.BadCredentialsException;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 *
 * @author yura
 */
public class GuestPreAuthUserDetailsService implements AuthenticationUserDetailsService {
    
    protected SystemSettingsManagement settingsManagement;
    protected UserManagement userManagement;
    protected boolean available = true;

    public GuestPreAuthUserDetailsService(
            SystemSettingsManagement settingsManagement, 
            UserManagement userManagement) {
        this.settingsManagement = settingsManagement;
        this.userManagement = userManagement;
    }

    public void setAvailable(boolean available) {
        this.available = available;
    }

    @Override
    public UserDetails loadUserDetails(Authentication token) 
            throws UsernameNotFoundException {
        boolean withPrincipial = token != null && token.getPrincipal() != null;

        if (withPrincipial && !"GuestAuthentication".equals(token.getPrincipal())){
            throw new BadCredentialsException("Not guest principal");
        }
        
        boolean guesAvail = settingsManagement.getBoolean(AvailableGuest);
        DefaultAuthenticationOption defaultAuth = settingsManagement
                .getDefaultAuthenticationOption(DefaultAuthentication);
        
        if (available && guesAvail && (defaultAuth == GuestCredentials || withPrincipial)) {
            return new UserDetailsData(userManagement.getGuestAccount());
        }
        
        throw new UsernameNotFoundException("Guest account is unavailable");
    }
    
    
}
